import { ColumnProps, ImageProps, UserProps } from "@/store/index";
export function generateFitUrl(data: ImageProps, width: number, height: number, format = ['m_pad']) {
	if (data && data.url) {
		const formatStr = format.reduce((prev, current) => {
			return current + ',' + prev
		}, '')
		data.fitUrl = data.url + `?x-oss-process=image/resize,${formatStr}h_${height},w_${width}`
	}
}

// ！！！！！！！！！！！！！！！！！！！！！！
// export function addColumnAvatar(data: ColumnProps | UserProps, width: number, height: number) {
// 	if (data.avatar) {
// 		generateFitUrl(data.avatar, width, height)
// 	} else {
// 		const parseCol = data as ColumnProps
// 		data.avatar = {
// 			fitUrl: require(parseCol.title ? '@/assets/column.jpg' : '@/assets/avatar.jpg')
// 		}
// 	}
// }


interface CheckCondition {
	format?: string[];
	size?: number;
}
// 错误类型
type ErrorType = 'size' | 'format' | null
// file 传入的文件， condition 检验规则
export const beforeUploadCheck = (file: File, condition: CheckCondition) => {
	const { format, size } = condition;

	// 检验文件类型和文件大小。format, size 如果没传入，默认就都返回true
	// 检验文件类型是否合法
	const isValidFormat = format ? format.includes(file.type) : true;
	// 检验文件大小
	// 文件上传时，size是字节，要转成兆，
	const isValidSize = size ? (file.size / 1024 / 1024) < size : true;
	let error: ErrorType = null
	if (!isValidFormat) {
		error = 'format'
	}
	if (!isValidSize) {
		error = 'size'
	}
	return {
		passed: isValidFormat && isValidSize,
		error
	}
};


// 数组转对象
export const arrToObj = <T extends { _id?: string }>(arr: Array<T>) => {
	return arr.reduce((prev, current) => {
		if (current._id) {
			prev[current._id] = current
		}
		return prev
	}, {} as { [key: string]: T })
}
// 对象转数组
export const objToArr = <T>(obj: { [key: string]: T }) => {
	return Object.keys(obj).map(key => obj[key])
}